import React, { Component } from 'react';
import { Card, Form, Input, Button, Checkbox, message } from 'antd';
import Styles from './index.module.scss';
import { login, getCode } from 'api/user';
import { setToken } from 'utils/storage';

export default class Login extends Component {
  inpRef = React.createRef();
  onFinish = async (values) => {
    console.log('表单数据', values);
    // if (!remember) {
    //   message.warning('请阅读隐私条款和用户协议');
    //   return;
    // }
    const res = await login(values);
    // 保存token
    setToken(res.data.token);
    // 提示用户登录成功
    message.success('登录成功');
    // 跳转页面
    this.props.history.push('/layout');
  };
  getCode = async () => {
    const mobile = this.inpRef.current.input.value;
    await getCode(mobile);
  };
  render() {
    const imgSrc = require('assets/logo.png');
    return (
      <div className={Styles.login}>
        <Card>
          <img className="logo" src={imgSrc} alt="" />
          {/* 表单 */}
          <Form
            initialValues={{
              mobile: '13811111111',
            }}
            name="basic"
            autoComplete="off"
            onFinish={this.onFinish}
            validateTrigger={['onBlur', 'onChange']}
          >
            <Form.Item
              name="mobile"
              rules={[
                { required: true, message: '请输入手机号!' },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入正确的11位手机号',
                },
              ]}
            >
              <Input ref={this.inpRef} placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item
              rules={[
                { required: true, message: '请输入验证码!' },
                {
                  pattern: /^\d{6}$/,
                  message: '验证码格式错误',
                },
              ]}
            >
              <Form.Item name="code">
                <Input placeholder="请输入验证码" className="code-input" />
              </Form.Item>
              <span className="code" onClick={this.getCode}>
                获取验证码
              </span>
            </Form.Item>

            <Form.Item
              name="remember"
              valuePropName="checked"
              rules={[
                {
                  validator: (_, value) =>
                    value
                      ? Promise.resolve()
                      : Promise.reject(new Error('请阅读隐私条款和用户协议')),
                },
              ]}
            >
              <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    );
  }
}
